<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use AlibabaCloud\SDK\ICE\V20201109\Models\SubmitDNAJobRequest\input;
use app\admin\model\ClipMission;
use app\admin\model\ClipModel;
use app\admin\model\ClipProject;
use app\admin\model\ClipTitle;
use app\admin\model\ClipVideoRepost;
use app\admin\model\FigureAiTitle;
use app\admin\model\FigureThreePartiesAccount;
use app\admin\model\ScanTask;
use app\admin\model\ScanTaskTitle;
use app\admin\model\ScanTaskVideo;
use app\admin\model\ThreeAccountGroup;
use app\admin\model\ThreeClipVideo;
use app\admin\model\ThreeComment;
use app\admin\model\ThreeCopywriting;
use app\admin\model\ThreePartiesQrcode;
use app\admin\model\ThreeTitle;
use app\admin\model\ThreeVideoReleaseTask;
use app\admin\model\ThreeVideoTask;
use app\BaseController;
use app\common\service\AgentApiService;
use app\common\service\ApiService;
use app\common\service\KuaishouService;
use app\common\service\YuntuituiService;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureAicreate;
use app\common\service\AIService;

/**
 * AI创作操作
 *
 * @author Administrator
 *
 */
class ExternalAccount extends BaseController
{

//http://aigc.weijuyunke.cn/mobile/externalAccount/douyinQrcode
    public function douyinQrcode()
    {
        $request = $this->request;
        $param = $request->param();
        $pid = $param['province_id'];            #省份 -1表示中国
        $cid = $param['city_id'];
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $liuguanIp = getliuguan($pid, $cid);
        if ($liuguanIp['code'] == 1) {
            $proxy = $liuguanIp['data']['ip'];
        } else {
            return result(-1, $liuguanIp['msg']);
        }
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        /*$tally = sysconfig('tally', 'douyin_scan_code');
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }*/
        $cookie = '';
        if (isset($param['cookie']) && $param['cookie']){

            $cookie =  $param['cookie'];
        }
        $result = $apiService->douyinQrcode(['proxy'=>$proxy,'cookie' => $cookie]);
        if (isset($result['code']) && $result['code'] == 1) {
            $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
            $data['qrcode_index_url'] = $result['data']['data']['qrcode_index_url'];
            $data['qrcode'] = $result['data']['data']['qrcode'];
            $data['expire_time'] = $result['data']['data']['expire_time'];
            $data['token'] = $result['data']['data']['token'];
            $data['cookie'] = $result['data']['cookie'];
            $data['proxy'] = $proxy;
            $data['uid'] = $param['uid'];
            $data['account_group_id'] = $param['account_group_id'];
            $data['province_id'] = $param['province_id'];            #省份 -1表示中国
            $data['city_id'] = $param['city_id'];
            $ThreePartiesQrcodeModel->save($data);
            $log_no = getPayNo('dsc');
          //  user_balance_used($param['uid'],$log_no, 2, 22);
            return result(0, 'success', $ThreePartiesQrcodeModel);
        } else {
            return result(-1, $result['msg']);
        }

    }

    public function douyinQrcodeCheck()
    {
        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }

        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
        if (empty($info)) {
            return result(-1, '数据有误');
        }

        $body['proxy'] = $info['proxy'];
        $body['token'] = $info['token'];
        $body['cookie'] = $info['cookie'];
        $result = $apiService->douyinQrcodeCheck($body);


        if (isset($result['code']) && $result['code'] == 1) {



            if ($result['data']['data']['error_code'] == 0 && $result['data']['data']['status'] =='scanned'  ) {
                return result(-4, 'success');
            }
            if ($result['data']['data']['error_code'] == 0 && $result['data']['data']['status'] =='new'  ) {
                return result(-3, 'success');
            }
            if ($result['data']['data']['error_code'] == 0 && $result['data']['data']['status'] =='expired'  ) {
                return result(-1, 'success');
            }
            if ($result['data']['data']['error_code'] == 2046  ) {

                $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
                $data['status'] = 2;
                $data['encrypt_uid'] = $result['data']['data']['encrypt_uid'];
                $ThreePartiesQrcodeModel->where(['id' => $param['id']])->save($data);
                $resultCode = $apiService->douyinSendSms(['encrypt_uid' => $data['encrypt_uid'], 'token' => $info['token'],'cookie'=>$info['cookie']]);
               if (isset($resultCode['code']) && $resultCode['code'] == 1) {

                   if (isset($resultCode['data']['data']['error_code']) && $resultCode['data']['data']['error_code'] == 1){
                       return result(-4, 'success', $resultCode);
                   }
                    $ThreePartiesQrcodeModel->where(['id' => $param['id']])->save(['status' => 3]);
                    return result(0, 'success', []);
                } else {
                    return result(-1, $result['msg']);
                }
            }
            if ($result['data']['data']['error_code'] == 0 && $result['data']['data']['status'] =='confirmed'  ){
                    $therrAccountData = [
                     //   'account_name' => $resultUserInfo['data']['user']['nickname'],
                        'status' => 1,
                     //   'avatar' => $resultUserInfo['data']['data']['user_data']['avatar_url'],
                        'cookie' => $result['data']['cookie'],
                        'qrcode_id' => $param['id'],
                        'uid' => $param['uid'],
                        'douyin_uid' => $result['data']['data']['user_data']['sec_user_id'],
                        'is_delete' => 1,
                        //  'account_group_id' => $info['account_group_id'],
                        //'exposure_count' => $resultUserInfo['data']['user']['avatar_medium']['url_list'][0],
                        'province_id' => $info['province_id'],
                        'city_id' => $info['city_id'],
                        'expires_in' => time() + (15 * 86400),

                    ];
                    $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                    $FigureThreePartiesAccountInfo = $FigureThreePartiesAccountModel->where(['douyin_uid'=>$result['data']['data']['user_data']['sec_user_id'],'uid' =>  $param['uid']])->find();
                    $log_no = getPayNo('da');
                    if (empty($FigureThreePartiesAccountInfo)){
                        $therrAccountData['account_group_id']  = $info['account_group_id'];
                        $FigureThreePartiesAccountModel->save($therrAccountData);
                        $threeAccountGroupModel = new ThreeAccountGroup();
                        $threeAccountGroupModel->where(['id' => $info['account_group_id']])->inc('account_count')->update();
                    }else{

                        $FigureThreePartiesAccountModel->where(['id' =>$FigureThreePartiesAccountInfo['id'] ])->update($therrAccountData);
                    }
                    return result(5, '授权成功', $FigureThreePartiesAccountModel);

            }

            return result(0, 'success', $ThreePartiesQrcodeModel);
        } else {
            return result(-1, $result['msg']);
        }
    }


    public function douyinVerifySms()
    {
        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
        if (empty($info)) {
            return result(-1, '数据有误');
        }
        $result = $apiService->douyinVerifySms([
            'encrypt_uid' => $info['encrypt_uid'],
            'code' => $param['code'],
            'token' => $info['token'],
            'cookie' => $info['cookie'],
        ]);
        if (isset($result['code']) && $result['code'] == 1) {

            $uid = input('uid');
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $tally = sysconfig('tally', 'douyin_authorize');
            $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
            $info = $ThreePartiesQrcodeModel->where(['id' => $param['id']])->find();
            $body['proxy'] = $info['proxy'];
            $body['token'] = $info['token'];
            $body['cookie'] = $info['cookie'];
            $ThreePartiesQrcodeModel->where(['id' => $param['id']])->save(['status' => 4]);
            $resultcookie = $apiService->douyinCookie($body);

            if (isset($resultcookie['code']) && $resultcookie['code'] == 1) {
                if (isset($resultcookie['data']['cookie']) && $resultcookie['data']['cookie']) {
                    $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
                    $data['cookie'] = $resultcookie['data']['cookie'];
                    $data['status'] = 5;
                    $ThreePartiesQrcodeModel->where(['id' => $param['id']])->save($data);
                    if (sysconfig('account', 'operation_version') == 2) {
                        $apiService = new AgentApiService();
                    } else {
                        $apiService = new ApiService();
                    }
                    $resultUserInfo = $apiService->douyinAuthorizeUserInfo($data);

                    if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                        if ($resultUserInfo['data']['status_code'] == 0) {
                            $therrAccountData = [
                                'account_name' => $resultUserInfo['data']['user']['nickname'],
                                'status' => 1,
                                'avatar' => $resultUserInfo['data']['user']['avatar_medium']['url_list'][0],
                                'cookie' => $resultcookie['data']['cookie'],
                                'qrcode_id' => $param['id'],
                                'uid' => $param['uid'],
                                'douyin_uid' => $resultUserInfo['data']['user']['sec_uid'],
                                'is_delete' => 1,
                                //  'account_group_id' => $info['account_group_id'],
                                //'exposure_count' => $resultUserInfo['data']['user']['avatar_medium']['url_list'][0],
                                'province_id' => $info['province_id'],
                                'city_id' => $info['city_id'],
                                'expires_in' => time() + (15 * 86400),

                            ];
                            $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                            $FigureThreePartiesAccountInfo = $FigureThreePartiesAccountModel->where(['douyin_uid'=>$resultUserInfo['data']['user']['sec_uid'],'uid' =>  $param['uid']])->find();
                            $log_no = getPayNo('da');
                            if (empty($FigureThreePartiesAccountInfo)){
                                $therrAccountData['account_group_id']  = $info['account_group_id'];
                                $FigureThreePartiesAccountModel->save($therrAccountData);
                                $threeAccountGroupModel = new ThreeAccountGroup();
                                $threeAccountGroupModel->where(['id' => $info['account_group_id']])->inc('account_count')->update();
                            }else{
                                if ($FigureThreePartiesAccountInfo['is_delete'] == 2){
                                    $threeAccountGroupModel = new ThreeAccountGroup();
                                    $threeAccountGroupModel->where(['id' => $FigureThreePartiesAccountInfo['account_group_id']])->inc('account_count')->update();
                                }
                                $FigureThreePartiesAccountModel->where(['id' =>$FigureThreePartiesAccountInfo['id'] ])->update($therrAccountData);
                            }
                            return result(0, '授权成功', $FigureThreePartiesAccountModel);
                        }else{
                            return result(-1, '授权失败');
                        }
                    } else {
                        return result(-1, $result['msg']);
                    }
                } else {
                    return result(-1, '用户信息获取失败');
                }
                return result(0, 'success', $ThreePartiesQrcodeModel);
            } else {
                return result(-1, $result['msg']);
            }
            return result(0, '授权成功', $info);
        } else {
            return result(-1, $result['msg']);
        }
    }

    /*    public function  douyinUserInfo(){
            $request = $this->request;
            $param = $request->param();
            $apiService = new ApiService();
            $result = $apiService->douyinUserInfo($param);
            if (isset($result['code']) && $result['code'] == 1) {
                $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                $data['mobile'] = $result['data']['mobile'];
               // $FigureThreePartiesAccountModel->where(['token'=> $result['data']['token']])->save($data);
                return result(0, 'success', $result['data']);
            } else {
                return result(-1, $result['msg']);
            }
       } */
    public function shipinghaoQrcode()
    {
        $request = $this->request;
        $param = $request->param();
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        $pid = $param['province_id'];            #省份 -1表示中国
        $cid = $param['city_id'];
        $liuguanIp = getliuguan($pid, $cid);
       if ($liuguanIp['code'] == 1) {
            $proxy = $liuguanIp['data']['ip'];
        } else {
            return result(-1, $liuguanIp['msg']);
        }
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'shipinhao_scan_code');
      /*  if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }*/

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->shipinghaoQrcode($proxy);

        $data['customize_account_name'] = $param['customize_account_name'];
        $data['customize_account_name'] = $param['customize_account_name'];
        $data['province_id'] = $param['province_id'];            #省份 -1表示中国
       $data['city_id'] = $param['city_id'];
        $domain = $request->domain();
        $data['customize_account_avatar'] = $domain . "/imgs/shipinghao.png";;
        $data['uid'] = $param['uid'];
        $data['account_group_id'] = $param['account_group_id'];
        if (isset($result['code']) && $result['code'] == 1) {
            $ThreePartiesQrcodeModel = new ThreePartiesQrcode();

            $data['qrcode'] =    common_qr_code($result['data']['qr_code'], 'repost'); ;
            $data['token'] = $result['data']['data']['token'];
            $log_no = getPayNo('spsc');
           // user_balance_used($param['uid'],$log_no, 2, 24);
            $ThreePartiesQrcodeModel->save($data);
            return result(0, 'success', $ThreePartiesQrcodeModel);
        } else {
            return result(-1, $result['msg']);
        }
    }

    public function shipinghaoeQrcodeCheck()
    {
        $request = $this->request;
        $param = $request->param();
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'shipinghao_authorize');
       /* if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }*/

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
       $liuguanIp = getliuguan($info['province_id'], $info['city_id']);
        if ($liuguanIp['code'] == 1) {
            $proxy = $liuguanIp['data']['ip'];
        } else {
            return result(-1, $liuguanIp['msg']);
        }
        if (empty($info)) {
            return result(-1, '数据有误');
        }
        $body['token'] = $info['token'];
        $body['proxy'] = $proxy;
        $result = $apiService->shipinghaoeQrcodeCheck($body);

        if (isset($result['code']) && $result['code'] == 1) {
            if (isset($result['data']['cookie']) && $result['data']['cookie']) {
                $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
                $data['cookie'] = $result['data']['cookie'];
                $ThreePartiesQrcodeModel->where(['id' => $param['id']])->save($data);

                $therrAccountData = [
                    'account_name' => $info['customize_account_name'],
                    'status' => 1,
                    'avatar' => $info['customize_account_avatar'],
                    'cookie' => $result['data']['cookie'],
                    'qrcode_id' => $param['id'],
                    'type' => 3,
                    'uid' => $param['uid'],
                    'account_group_id' => $info['account_group_id'],
                    'expires_in' => time() + 86400,
                    'is_delete' => 1,
                    'province_id' => $info['province_id'],
                    'city_id' => $info['city_id'],

                ];
                $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                $FigureThreePartiesAccountModel->save($therrAccountData);
                $threeAccountGroupModel = new ThreeAccountGroup();

                $threeAccountGroupModel->where(['id' => $info['account_group_id']])->inc('account_count')->update();
                $log_no = getPayNo('spa');
                //user_balance_used($param['uid'],$log_no, 2, 25);
                return result(0, '授权成功', $FigureThreePartiesAccountModel);
            } else {
                return result(-3, $result['msg']);
            }

        } else {
            return result(-1, $result['msg']);
        }
    }

    /**
     * 生成快手二维码
     */
    public function kuaishouQrcode()
    {
        $request = $this->request;
        $param = $request->param();
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $KuaishouService = new KuaishouService();
        $data['expire_time'] = time() + 60;
        $data['uid'] = $param['uid'];
        $data['account_group_id'] = $param['account_group_id'];
        $ThreePartiesQrcodeModel->save($data);
        $result = $KuaishouService->kuaishouQrcode($param ['uid'], $ThreePartiesQrcodeModel['id']);
        $data['qrcode'] = $result['data'];
        $ThreePartiesQrcodeModel->save($data);;
        return result(0, 'success', $ThreePartiesQrcodeModel);
    }

    /**
     * 快手回调
     */
    public function kuaishouQrcodeRedirect()
    {
        $forwardSet = sysconfig('forward');
        $request = $this->request;
        $param = $request->param();
        $k_appid = $forwardSet['k_appid'];
        $k_secret = $forwardSet['k_secret'];
        $uid = $param['uid'];
        $code = input('code');
        $url = "https://open.kuaishou.com/oauth2/access_token?app_id=" . $k_appid . "&app_secret=" . $k_secret . "&code=" . $code . "&grant_type=authorization_code";
        $obj = httpGet($url);
        $data = json_decode($obj, true);

        if ($data['result'] == 1) {
            $user_url = "https://open.kuaishou.com/openapi/user_info?app_id=" . $k_appid . "&access_token=" . $data['access_token'];
            $user_info = httpGet($user_url);
            $user_data = json_decode($user_info, true);
            $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
            $user = $FigureThreePartiesAccountModel->where('open_id', $data['open_id'])->where(['uid'  =>  $param['uid']])->find();
            $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
            $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
            $threeAccountData = array(
                'account_name' => $user_data['user_info']['name'],
                'open_id' => $data['open_id'],
                'type' => 2,
                'avatar' => $user_data['user_info']['head'],
                'access_token' => $data['access_token'],
                'uid' => $uid,
                'expires_in' => $data['expires_in'] + time(),
                'refresh_token' => $data['refresh_token'],
                'refresh_token_expires_in' => $data['refresh_token_expires_in'] + time(),
                'is_delete' => 1,
              //  'account_group_id' => $info['account_group_id']
            );
            if ($user) {
                if ($user['is_delete'] == 2){
                    $threeAccountGroupModel = new ThreeAccountGroup();
                    $threeAccountGroupModel->where(['id' => $user['account_group_id']])->inc('account_count')->update();
                }
                $FigureThreePartiesAccountModel->where(['id' => $user['id']])->update($threeAccountData);
            } else {
                $threeAccountData['account_group_id'] = $info['account_group_id'];
                $threeAccountGroupModel = new ThreeAccountGroup();
                $threeAccountGroupModel->where(['id' => $info['account_group_id']])->inc('account_count')->update();
                $FigureThreePartiesAccountModel->save($threeAccountData);
            }
            header('Location:' . request()->domain() . "/mobile/index/kshtml?uid=".$param['uid']."#/?type=2");
        } else {
            return result(-1, $data['error_msg']);
        }

    }

    public function xiaohongshuQrcode()
    {
        $request = $this->request;
        $param = $request->param();
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'xiaohongshu_scan_code');
      /*  if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }*/

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->xiaohongshuQrcode();
        if (isset($result['code']) && $result['code'] == 1) {
            $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
            $data['qrcode'] = $result['data']['base64_qr_code'];
            $data['code'] = $result['data']['code'];
            $data['qr_id'] = $result['data']['qr_id'];
            $data['cookie'] = $result['data']['cookie'];
            $data['uid'] = $param['uid'];
            $data['expire_time'] = time() + 60;
            $data['account_group_id'] = $param['account_group_id'];
            $ThreePartiesQrcodeModel->save($data);
            $log_no = getPayNo('xhsse');
            //user_balance_used($param['uid'],$log_no, 2, 26);
            return result(0, 'success', $ThreePartiesQrcodeModel);
        } else {
            return result(-1, $result['msg']);
        }
    }

    /**
     *验证小红书
     */
   /* public function xiaohongshuQrcodeCheck()
    {
        $request = $this->request;
        $param = $request->param();
        $apiService = new ApiService();
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
        $result = $apiService->xiaohongshuQrcodeCheck(['qr_id' => $info['qr_id'], 'code' => $info['code'], 'cookie' => $info['cookie']]);
        if (isset($result['code']) && $result['code'] == 1) {
            if (isset($result['data']['data'])) {
                if ($result['data']['data']['code_status'] == 0) {
                    return result(-4, 'success', $info);
                }
                if ($result['data']['data']['code_status'] == 3) {
                    return result(-3, 'success', $info);
                }
                if ($result['data']['data']['code_status'] == 2) {
                    return result(0, 'success', ['id' => $info['id'], 'cookie' => $result['data']['cookie']]);
                }
            } else {
                return result(-3, 'success', $info);
            }

            return result(0, 'success', $result['data']['cookie']);
        } else {
            return result(-1, $result['msg']);
        }
    }*/

    public function xiaohongshuUserInfo()
    {
        $request = $this->request;
        $param = $request->param();

        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'xiaohongshu_authorize');
       /* if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }*/

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
        $result = $apiService->xiaohongshuQrcodeCheck(['qr_id' => $info['qr_id'], 'code' => $info['code'], 'cookie' => $info['cookie']]);
        if (isset($result['code']) && $result['code'] == 1) {
            if (isset($result['data']['data'])){
                if ($result['data']['data']['code_status'] == 2) {
                    if (sysconfig('account', 'operation_version') == 2) {
                        $apiService = new AgentApiService();
                    } else {
                        $apiService = new ApiService();
                    }
                    $resultUserInfo = $apiService->xiaohongshuAuthorizeUserInfo(['cookie' => $result['data']['cookie']]);
                    if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                        if (isset($resultUserInfo['data']['response_body'])) {
                            if ($resultUserInfo['data']['response_body']['code'] == 0) {

                                $threeAccountData = [
                                    'account_name' => $resultUserInfo['data']['response_body']['data']['basic_info']['nickname'],
                                    'status' => 1,
                                    'avatar' => $resultUserInfo['data']['response_body']['data']['basic_info']['images'],
                                    'cookie' => $result['data']['cookie'],
                                    'qrcode_id' => $param['id'],
                                    'type' => 4,
                                    'uid' => $param['uid'],
                                    'is_delete' => 1,
                                    'expires_in' => time() + (180 * 86400),
                                    'red_id' => $resultUserInfo['data']['response_body']['data']['basic_info']['red_id'],

                                    //     'account_group_id' => $info['account_group_id']


                                ];
                                $log_no = getPayNo('xhsa');
                               // user_balance_used($param['uid'],$log_no, 2, 27);
                                $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                                $FigureThreePartiesAccountInfo = $FigureThreePartiesAccountModel->where(['red_id' => $resultUserInfo['data']['response_body']['data']['basic_info']['red_id'],'uid' =>  $param['uid']])->find();
                                if ($FigureThreePartiesAccountInfo) {
                                    $FigureThreePartiesAccountModel->where(['id' => $FigureThreePartiesAccountInfo['id']])->update($threeAccountData);
                                } else {
                                    $threeAccountData['account_group_id'] = isset($info['account_group_id']) ? $info['account_group_id'] : $param['account_group_id'];
                                    $ThreeAccountGroupModel = new ThreeAccountGroup();
                                    $ThreeAccountGroupModel->where(['id' => $info['account_group_id']])->inc('account_count')->update();
                                    $FigureThreePartiesAccountModel->save($threeAccountData);
                                }
                                return result(0, 'success', $resultUserInfo);
                            } else {
                                return result(-3, 'success', $info);
                            }
                        }
                    }
                    return result(-3, 'success', $info);
                }
            }

            if (isset($result['data']['response_body'])) {

               if (!isset($result['data']['response_body']['data']['code_status'])){
                    return result(-1, '账号授权失败');
                }
                if ($result['data']['response_body']['data']['code_status'] == 0) {
                    return result(-4, 'success', $result);
                }
                if ($result['data']['response_body']['data']['code_status'] == 3) {
                    return result(-3, 'success', $result);
                }
                if ($result['data']['response_body']['data']['code_status'] == 1) {
                    return result(-5, 'success', $result);
                }

            } else {
                return result(-3, 'success', $info);
            }
            return result(-3, 'success');
        } else {
            return result(-1, $result['msg']);
        }
    }

    /*
     * 通过小红书cookie 获取用户信息
     */
    public function xiaohongshuCookie()
    {
        $request = $this->request;
        $param = $request->param();
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'xiaohongshu_authorize');
       /* if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }*/
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        if (isset($param['id']) && $param['id']) {
            $info = $ThreePartiesQrcodeModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
        } else {
            $info = [];
        }

        $resultUserInfo = $apiService->xiaohongshuAuthorizeUserInfo(['cookie' => $param['cookie']]);

        if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
            if (isset($resultUserInfo['data']['response_body'])) {
                if ($resultUserInfo['data']['response_body']['code'] == 0) {
                    $threeAccountData = [
                        'account_name' => $resultUserInfo['data']['response_body']['data']['basic_info']['nickname'],
                        'status' => 1,
                        'avatar' => $resultUserInfo['data']['response_body']['data']['basic_info']['images'],
                        'cookie' => $param['cookie'],
                        'qrcode_id' => isset($param['id'])? $param['id']:0,
                        'type' => 4,
                        'uid' => $param['uid'],
                       // 'account_group_id' => isset($info['account_group_id']) ? $info['account_group_id'] : $param['account_group_id'],
                        'expires_in' => time() + (180 * 86400),
                        'red_id' => $resultUserInfo['data']['response_body']['data']['basic_info']['red_id'],
                        'is_delete' => 1

                    ];
                    $log_no = getPayNo('xhsa');
                    //user_balance_used($param['uid'],$log_no, 2, 27);
                    $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                    $FigureThreePartiesAccountInfo = $FigureThreePartiesAccountModel->where(['red_id' => $resultUserInfo['data']['response_body']['data']['basic_info']['red_id'],'uid' =>  $param['uid']])->find();
                    if ($FigureThreePartiesAccountInfo) {
                        if ($FigureThreePartiesAccountInfo['is_delete'] == 2){
                            $threeAccountGroupModel = new ThreeAccountGroup();
                            $threeAccountGroupModel->where(['id' => $FigureThreePartiesAccountInfo['account_group_id']])->inc('account_count')->update();
                        }
                        $FigureThreePartiesAccountModel->where(['id' => $FigureThreePartiesAccountInfo['id']])->update($threeAccountData);
                    } else {
                        $threeAccountData['account_group_id'] = isset($param['account_group_id']) ? $param['account_group_id'] : $param['account_group_id'];
                        $ThreeAccountGroupModel = new ThreeAccountGroup();
                        $ThreeAccountGroupModel->where(['id' => $param['account_group_id']])->inc('account_count')->update();
                        $FigureThreePartiesAccountModel->save($threeAccountData);
                    }

                    return result(0, '授权成功', $FigureThreePartiesAccountModel);
                } else {
                    return result(-1, '失败');
                }
            }
        }
        return result(-1, '失败', []);
    }


    public function bzhangQrcode()
    {
        $request = $this->request;
        $param = $request->param();
        $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
        $KuaishouService = new KuaishouService();
        $result = $KuaishouService->bzhangQrcode($param ['uid']);
        $data['qrcode'] = $result['data'];
        $data['expire_time'] = time() + 60;
        $data['uid'] = $param['uid'];
        $ThreePartiesQrcodeModel->save($data);
        return result(0, 'success', $ThreePartiesQrcodeModel);
    }


    /**
     *  账号列表
     */
    public function accountList()
    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $where = 'uid = ' . $uid;
            $where .= '  AND is_delete =  1 ';
            if (!empty(input('account_name'))) {
                $name = input('account_name');
                $where .= " AND account_name LIKE '%{$name}%' ";

            }
            if (!empty(input('account_group_id'))) {
                $account_group_id = input('account_group_id');
                $where .= " AND account_group_id = {$account_group_id} ";
            }


            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = {$type} ";
            }

            $total = FigureThreePartiesAccount::where($where)->count();

            $threeAccountGroupModel = new ThreeAccountGroup();
            if ($total) {
                $list = FigureThreePartiesAccount::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                foreach ($list as $key => $value) {
                    $threeAccountGroupInfo = $threeAccountGroupModel->where(['id' => $value['account_group_id']])->find();
                    if ($threeAccountGroupInfo) {
                        $list[$key]['account_group_name'] = $threeAccountGroupInfo['name'];
                        $list[$key]['expires_in'] = date('Y-m-d H:i', $value['expires_in']);
                        $videoTotal = ThreeVideoReleaseTask::where('three_account_id', '=', $value['id'])
                            ->field('sum(comment) as comment_total ,sum(exposure_count) as exposure_count_total ,sum(like_count) as like_count_total ')
                            ->find();
                        $list[$key]['comment'] = $videoTotal['comment_total'] ? $videoTotal['comment_total'] : 0;
                        $list[$key]['exposure_count'] = $videoTotal['exposure_count'] ? $videoTotal['exposure_count'] : 0;
                        $list[$key]['like_count'] = $videoTotal['like_count'] ? $videoTotal['like_count'] : 0;
                        if ($value['totle_task'] > 0) {
                            $list[$key]['percentage'] = bcmul(bcdiv($value['published_task'], $value['totle_task'], 2), 100);

                        } else {
                            $list[$key]['percentage'] = 0;

                        }

                    } else {
                        $list[$key]['account_group_name'] = 0;
                        $list[$key]['expires_in'] = date('Y-m-d H:i', $value['expires_in']);

                        $list[$key]['comment'] = 0;
                        $list[$key]['exposure_count'] = 0;
                        $list[$key]['like_count'] = 0;
                        $list[$key]['percentage'] = 0;

                    }

                }
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 删除账号
     */
    public function delAccount()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $id = input('id');
        $ThreeVideoTaskModel = new ThreeVideoTask();
        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        foreach ($id as $value) {
            $info = FigureThreePartiesAccount::where(['id' => $value])->find();
            $threeAccountGroupModel = new ThreeAccountGroup();
            $threeAccountGroupModel->where(['id' => $info['account_group_id']])
                ->dec('account_count', 1)->update();
            FigureThreePartiesAccount::where(['id' => $value])->update(['is_delete' => 2]);
            $ThreeVideoTaskModel->where(['three_account_id' => $value,'status' =>1])->update(['delete_time' => time()]);
           $ThreeVideoReleaseTaskModel->where(['three_account_id' => $value,'status' =>1])->update(['delete_time' => time()]);

        }

        return result(0, '删除成功', []);
    }

    /**
     * 添加账号分组
     */
    public function addAccountGroup()
    {
        $request = $this->request;
        $param = $request->param();
        $threeAccountGroupModel = new ThreeAccountGroup();
        $data = [
            'name' => $param['name'],
            'type' => $param['type'],
            'uid' => $param['uid']
        ];
        $threeAccountGroupModel->save($data);
        return result(0, '添加成功', $threeAccountGroupModel);
    }


    public function delAccountGroup()
    {
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $threeAccountGroupModel = new ThreeAccountGroup();
        $threeAccountGroupInfo = $threeAccountGroupModel->where(['id' => $param['id'], 'uid' => $param['uid']])->find();
        if ($threeAccountGroupInfo['account_count'] > 0) {
            return result(-1, '分组下有账号,请先移除');
        }
        if ($threeAccountGroupInfo) {
            $threeAccountGroupInfo->delete();
        } else {
            return result(-1, '分组不存在');
        }
        return result(0, '删除成功');
    }

    public function accountGroupList()
    {
        try {
            $uid = input('uid');
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where = 'uid = ' . $uid;
            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%' ";
            }
            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = {$type} ";
            }
            $total = ThreeAccountGroup::where($where)->count();
            if ($total) {
                $list = ThreeAccountGroup::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                foreach ($list as $key => $value) {
                    $accountList = FigureThreePartiesAccount::where(['account_group_id' => $value['id']])->select()->toArray();

                    if ($accountList) {
                        $accountId = array_column($accountList, 'id');
                        $videoTotal = ThreeVideoReleaseTask::where('three_account_id', 'in', $accountId)
                            ->field('sum(comment) as comment_total ,sum(exposure_count) as exposure_count_total ,sum(like_count) as like_count_total ')
                            ->find();

                        $list[$key]['comment'] = $videoTotal['comment_total'] ? $videoTotal['comment_total'] : 0;
                        $list[$key]['exposure_count'] = $videoTotal['exposure_count'] ? $videoTotal['exposure_count'] : 0;
                        $list[$key]['like_count'] = $videoTotal['like_count'] ? $videoTotal['like_count'] : 0;
                        $list[$key]['account_count'] =  FigureThreePartiesAccount::where(['account_group_id' => $value['id']])->where(['is_delete' => 1])->count();
                    }
                }
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function accountExchangeGroup()
    {
        $uid = input('uid');
        $id = input('id');
        $groupId = input('account_group_id');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        foreach ($id as $value) {
            $accountInfo = FigureThreePartiesAccount::where(['id' => $value, 'uid' => $uid])->find();

            try {
                $threeAccountGroupModel = new ThreeAccountGroup();
                $threeAccountGroupModel->startTrans();

                $threeAccountGroupModel->where(['id' => $accountInfo['account_group_id']])
                    ->dec('account_count', 1)->dec('exposure_count', $accountInfo['exposure_count'])
                    ->dec('like_count', $accountInfo['like_count'])
                    ->dec('comment', $accountInfo['comment'])
                    ->update();
                FigureThreePartiesAccount::where(['id' => $accountInfo['id']])->update(['account_group_id' => $groupId]);
                $threeAccountGroupModel->where(['id' => $groupId])
                    ->inc('account_count', 1)
                    ->inc('exposure_count', $accountInfo['exposure_count'])
                    ->inc('like_count', $accountInfo['like_count'])
                    ->inc('comment', $accountInfo['comment'])
                    ->update();
                $threeAccountGroupModel->commit();
                return result('0', '操作成功');
            } catch (\Exception $exception) {
                $threeAccountGroupModel->rollback();
                return result(-1, $exception->getMessage());
            }
        }


    }

    public function addVideoTaskOne()
    {

        $dayData = ['7:00', '7:30', '8:00', '8:30', '9:00', '9:30', '10:00', '10:30', '11:00', '11:30',
            '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30',
            '17:00', '17:30', '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30',
            '22:00', '22:30', '23:00', '23:30', '24:00'];
        $dayTimeCount = count($dayData) - 1;
        $request = $this->request;
        $param = $request->param();
        $ThreeVideoTaskModel = new ThreeVideoTask();
        try {
            $data = [
                'uid' => $param['uid'],
                'name' => $param['name'],
                'mount_type' => $param['mount_type'],
                'city' => isset($param['city']) ? $param['city'] : '',
                'poi' => isset($param['poi']) ? $param['poi'] : '',
                'poi_address' => isset($param['poi_address']) ? $param['poi_address'] : '',
                'shop_name' => isset($param['shop_name']) ? $param['shop_name'] : '',
                'release_type' => $param['release_type'],
                'release_day_count' => $param['release_day_count'],
                'release_everyday_count' => $param['release_everyday_count'],
                'channle_type' => $param['type'],
                'three_account_id' => $param['account_id']
            ];
            if (isset($param['startDate']) && $param['startDate']) {
                $threeReleaseVideoTask['startDate'] = strtotime($param['startDate']);
            }
            $FigureThreePartiesAccount = new  FigureThreePartiesAccount();
            $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $param['account_id']])->find();
            if ($accountInfo['status'] == 2) {
                return result(-1, '此帐号授权过期');
            }
            if ($param['type'] == 1) {
                $ClipProjectWhere = ['is_douyin' => 1];
                $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
                if ($liuguanResult['code'] == 1) {
                    $apiService = new ApiService();
                    $resultUserInfo = $apiService->douyinUserInfo(['cookie' => $accountInfo['cookie']]);
                    if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                        if ($resultUserInfo['data']['status_code'] != 0) {
                            $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                            return result(-1, '此帐号授权过期');
                        }
                    } else {
                        return result(-1, '抖音账号获取失败,请刷新重试');
                    }
                } else {
                    return result(-1, $liuguanResult['msg']);
                }
            } elseif ($param['type'] == 2) {
                $ClipProjectWhere = ['is_kuaishou' => 1];
                if ($accountInfo['expires_in'] > time()) {
                    $kuaishouService = new KuaishouService();
                    $kuiShouInfo = $kuaishouService->kuaishouUserinfo($accountInfo['access_token']);
                    if ($kuiShouInfo['code'] == 0) {
                        $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                        return result(-1, '此帐号授权过期');
                    }
                } else {
                    if ($accountInfo['refresh_token_expires_in'] < 0) {
                        $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                        return result(-1, '此帐号授权过期');
                    }
                    $kuaishouService = new KuaishouService();
                    $kuiShouInfo = $kuaishouService->kuaishouRefreshToken($accountInfo['refresh_token_expires_in']);
                    if ($kuiShouInfo['code'] == 0) {
                        $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                        return result(-1, '此帐号授权过期');
                    } else { // 重新授权账号
                        $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                        $user = $FigureThreePartiesAccountModel->where('open_id', $kuiShouInfo['open_id'])->find();
                        $threeAccountData = array(
                            'account_name' => $kuiShouInfo['user_info']['name'],
                            'avatar' => $kuiShouInfo['user_info']['head'],
                            'access_token' => $kuiShouInfo['access_token'],
                            'expires_in' => $kuiShouInfo['expires_in'] + time(),
                            'refresh_token' => $kuiShouInfo['refresh_token'],
                        );
                        if ($user) {
                            $FigureThreePartiesAccountModel->where(['id' => $user['id']])->update($threeAccountData);
                        } else {
                            $FigureThreePartiesAccountModel->save($threeAccountData);
                        }
                    }
                }
            } elseif ($param['type'] == 3) {
                $ClipProjectWhere = ['is_shipinghao' => 1];
                /* $apiService = new ApiService();
                 $ThreePartiesQrcodeModel = new ThreePartiesQrcode();
                 $info = $ThreePartiesQrcodeModel->where(['id' => $accountInfo['qrcode_id']])->find();
                 if (empty($info)) {
                     return result(-1, '数据有误');
                 }
                 $body['token'] = $info['token'];
                 $result = $apiService->shipinghaoeQrcodeCheck($body);
                 if (isset($result['code']) && $result['code'] == 1) {
                     if (!isset($result['data']['cookie'])) {
                         $FigureThreePartiesAccount->where(['id' => $accountInfo['access_token']])->update(['status' => 2]);
                         return result(-1, '此帐号授权过期');
                     }
                 }*/
            } elseif ($param['type'] == 4) {
                $ClipProjectWhere = ['is_xiaohongshu' => 1];
                $apiService = new ApiService();
                $resultUserInfo = $apiService->xiaohongshuUserInfo(['cookie' => $accountInfo['cookie']]);
                if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                    if (isset($resultUserInfo['data']['response_body'])) {
                        if ($resultUserInfo['data']['response_body']['code'] != 0) {
                            $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                            return result(-1, '此帐号授权过期');
                        }
                    }
                }
            }
            $ThreeVideoTaskModel->startTrans();
            $ThreeVideoTaskModel->save($data);
            if (isset($param['copywiring'])) {
                $copywiring = explode(',', $param['copywiring']);
                if ($copywiring) {
                    $ThreeCopywritingModel = new ThreeCopywriting();
                    foreach ($copywiring as $value) {
                        $copywiringData['copywriting_id'] = $value;
                        $copywiringData['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $ThreeCopywritingModel->save($copywiringData);
                    }
                }
            }


            $titleId = explode(',', $param['title_id']);
            if ($titleId) {
                $ThreeTitleModel = new ThreeTitle();
                foreach ($titleId as $titleIdvalue) {
                    $titleData['title_id'] = $titleIdvalue;
                    $titleData['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                    $ThreeTitleModel->save($titleData);
                }
            }
            if ($param['clip_id']) {
                $clipId = explode(',', $param['clip_id']);
                if ($clipId) {
                    $clipModel = new ThreeClipVideo();
                    foreach ($copywiring as $value) {
                        $clipData['clip_id'] = $value;
                        $clipData['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $clipModel->save($clipData);
                    }
                }
            } else {
                return result(-1, '请选择视频');
            }
            $ClipProject = new ClipProject();

            $clipProjectList = $ClipProject->where('mission_id', 'in', $clipId)->where($ClipProjectWhere)->where(['status' => 5])->select()->toArray();

            if (empty($clipProjectList)) {
                return result(-1, '无视频发布');
            }
            if ($param['release_type'] == 1) {
                for ($i = 0; $i < $param['release_day_count']; $i++) {
                    $threeReleaseVideoTask = [];
                    if (empty($clipProjectList)) {
                        continue;
                    }
                    $everyVideoCount = 0;// 每天发布数量
                    foreach ($clipProjectList as $key => $value) {
                        if ($everyVideoCount == $param['release_everyday_count'] || $everyVideoCount >= 35) {
                            continue;
                        }
                        $TodayTime = strtotime(date("Y-m-d", strtotime($param['startDate'])));
                        $nextDayTime = $TodayTime + ($i) * 86400;
                        $nextDay = date("Y-m-d", $nextDayTime);
                        $dayTimeIndex = mt_rand(0, $dayTimeCount);
                        $release_time = strtotime($nextDay . ' ' . $dayData[$dayTimeIndex]);
                        $threeReleaseVideoTask['uid'] = $param['uid'];
                        $threeReleaseVideoTask['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $threeReleaseVideoTask['clip_project_video_id'] = $value['id'];
                        $threeReleaseVideoTask['three_account_id'] = $param['account_id'];
                        $threeReleaseVideoTask['channle_type'] = $param['type'];
                        $threeReleaseVideoTask['release_time'] = $release_time;
                        $threeReleaseVideoTask['name'] = $param['name'];
                        $threeReleaseVideoTask['create_time'] = time();
                        if ($param['topic_list']) {
                            $threeReleaseVideoTask['topic_list'] = $param['topic_list'];
                        }
                        if ($param['anchorUrl']) {
                            $threeReleaseVideoTask['anchorUrl'] = $param['anchorUrl'];
                        }
                        if ($param['anchorTitle']) {
                            $threeReleaseVideoTask['anchorTitle'] = $param['anchorTitle'];
                        }
                        if ($param['anchorId']) {
                            $threeReleaseVideoTask['anchorId'] = $param['anchorId'];
                        }

                        if ($copywiring) {
                            $ThreeCopywritingCount = count($copywiring);
                            $ThreeCopywritingIndex = mt_rand(0, $ThreeCopywritingCount - 1);
                            $threeReleaseVideoTask['copywriting_id'] = $copywiring[$ThreeCopywritingIndex];
                        }
                        if ($titleId) {
                            $titleIdCount = count($titleId);
                            $titleIdIndex = mt_rand(0, $titleIdCount - 1);
                            $threeReleaseVideoTask['ai_title'] = $titleId[$titleIdIndex];
                        }
                        $threeReleaseVideoTask['log_no'] = getPayNo('JZ');
                        $ThreeVideoReleaseTaskModel->insert($threeReleaseVideoTask);
                        $everyVideoCount++;


                        if ($param['type'] == 1) {
                            $ClipProject->where(['id' => $value['id']])->update(['is_douyin' => 2]);
                            user_balance_used($value['uid'], $threeReleaseVideoTask['log_no'], 2, 18);

                        } elseif ($param['type'] == 2) {
                            $ClipProject->where(['id' => $value['id']])->update(['is_kuaishou' => 2]);
                            user_balance_used($value['uid'], $threeReleaseVideoTask['log_no'], 2, 19);
                        } elseif ($param['type'] == 3) {
                            $ClipProject->where(['id' => $value['id']])->update(['is_shipinghao' => 2]);
                            user_balance_used($value['uid'], $threeReleaseVideoTask['log_no'], 2, 20);
                        } elseif ($param['type'] == 4) {
                            $ClipProject->where(['id' => $value['id']])->update(['is_xiaohongshu' => 2]);
                            user_balance_used($value['uid'], $threeReleaseVideoTask['log_no'], 2, 21);
                        }
                        unset($clipProjectList[$key]); //. 使用过的数据就删除
                    }
                }
            } else {
                $clipProjectList = $ClipProject->where('mission_id', 'in', $clipId)->where($ClipProjectWhere)->where(['status' => 5])->select()->toArray();
                if (empty($clipProjectList)) {
                    return result(-1, '无可用视频');
                }
                foreach ($param['set_time'] as $value) {
                    $clipProjectList = array_values($clipProjectList);
                    foreach ($clipProjectList as $key => $clipProjectListValue) {
                        $threeReleaseVideoTask['uid'] = $param['uid'];
                        $threeReleaseVideoTask['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $threeReleaseVideoTask['clip_project_video_id'] = $clipProjectListValue['id'];
                        $threeReleaseVideoTask['three_account_id'] = $param['account_id'];
                        $threeReleaseVideoTask['channle_type'] = $param['type'];
                        $threeReleaseVideoTask['release_time'] = strtotime($value);
                        $threeReleaseVideoTask['name'] = $param['name'];
                        $threeReleaseVideoTask['create_time'] = time();
                        if ($param['topic_list']) {
                            $threeReleaseVideoTask['topic_list'] = $param['topic_list'];
                        }
                        if ($param['anchorUrl']) {
                            $threeReleaseVideoTask['anchorUrl'] = $param['anchorUrl'];
                        }
                        if ($param['anchorTitle']) {
                            $threeReleaseVideoTask['anchorTitle'] = $param['anchorTitle'];
                        }
                        if ($param['anchorId']) {
                            $threeReleaseVideoTask['anchorId'] = $param['anchorId'];
                        }
                        if ($copywiring) {
                            $ThreeCopywritingCount = count($copywiring);
                            $ThreeCopywritingIndex = mt_rand(0, $ThreeCopywritingCount - 1);
                            $threeReleaseVideoTask['copywriting_id'] = $copywiring[$ThreeCopywritingIndex];
                        }
                        if ($titleId) {
                            $titleIdCount = count($titleId);
                            $titleIdIndex = mt_rand(0, $titleIdCount - 1);
                            $threeReleaseVideoTask['ai_title'] = $titleId[$titleIdIndex];
                        }
                        $threeReleaseVideoTask['log_no'] = getPayNo('JZ');
                        $ThreeVideoReleaseTaskModel->insert($threeReleaseVideoTask);
                    }
                }
            }
            $FigureThreePartiesAccount->where(['id' => $param['account_id']])
                ->inc('totle_task')->inc('released_task')->update();
            $ThreeVideoTaskModel->commit();
            return result(0, 'success', $ThreeVideoTaskModel);
        } catch (\Exception $exception) {
            $ThreeVideoTaskModel->rollback();
            return result(-1, $exception->getMessage() . $exception->getLine());
        }
    }


    public function addVideoTask()
    {
        $request = $this->request;
        $param = $request->param();
        $ThreeVideoTaskModel = new ThreeVideoTask();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        try {
            foreach ($param['set_time'] as $key => $value) {
                $accountIdArray[] = $value['dyAccountId'];
                $releaseTime[] = $value['publishTime'];
            }
            $data = [
                'uid' => $param['uid'],
                'name' => $param['name'],
                'city' => isset($param['city']) ? $param['city'] : '',
                'poi' => isset($param['poi']) ? $param['poi'] : '',
                'poi_address' => isset($param['poi_address']) ? $param['poi_address'] : '',
                'shop_name' => isset($param['shop_name']) ? $param['shop_name'] : '',
                'release_type' => $param['release_type'],
                'release_day_count' => $param['release_day_count'],
                'release_everyday_count' => $param['release_everyday_count'],
                'channle_type' => $param['type'],
                'three_account_id' => implode(',', $accountIdArray),
                'release_time' => implode(',', $releaseTime),

                /*'three_account_id' => implode( ',',$param['account_id']]*/
            ];
            if (  isset($param['mount_type'])){
                $data['mount_type'] = $param['mount_type'];
            }
            if (isset($param['topic_list'])) {
                $data['topic_list'] = $param['topic_list'];
            }
            if (isset($param['topic_name'])) {
                $data['topic_name'] = $param['topic_name'];
            }
            if (isset($param['anchorUrl'])) {
                $data['anchorUrl'] = $param['anchorUrl'];
            }
            if (isset($param['anchorTitle'])) {
                $data['anchorTitle'] = $param['anchorTitle'];
            }
            if (isset($param['anchorId'])) {
                $data['anchorId'] = $param['anchorId'];
            }
            if (isset($param['goods_id'])) {
                $data['goods_id'] = $param['goods_id'];
            }
            if (isset($param['startDate']) && $param['startDate']) {
                $data['startDate'] = strtotime($param['startDate']);
            }
            $FigureThreePartiesAccount = new  FigureThreePartiesAccount();
            $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
            /* $accountInfo = $FigureThreePartiesAccount->where(['id' => $param['account_id']])->find();
             if ($accountInfo['status'] == 2) {
                 return result(-1, '此帐号授权过期');
             }*/


            if ($param['type'] == 1) {

                $ClipProjectWhere = ['is_douyin' => 1];
                $videoCount = count($param['set_time']);
                $tally = sysconfig('tally', 'douying_video');
                if ($user['balance'] < $videoCount * $tally) {
                    return result(-2, '余额不足，请充值');
                }
                /* $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
                 if ($liuguanResult['code'] == 1) {
                     $apiService = new ApiService();
                     $resultUserInfo = $apiService->douyinUserInfo(['cookie' => $accountInfo['cookie']]);
                     if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                         if ($resultUserInfo['data']['status_code'] != 0) {
                             $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                             return result(-1, '此帐号授权过期');
                         }
                     } else {
                         return result(-1, '抖音账号获取失败,请刷新重试');
                     }
                 } else {
                     return result(-1, $liuguanResult['msg']);
                 }*/
            } elseif ($param['type'] == 2) {
                $ClipProjectWhere = ['is_kuaishou' => 1];
                $videoCount = count($param['set_time']);
//                $tally = sysconfig('tally', 'kuaishou_video');
//                if ($user['balance'] < $videoCount * $tally) {
//                    return result(-2, '余额不足，请充值');
//                }
                /* if ($accountInfo['expires_in'] > time()) {
                     $kuaishouService = new KuaishouService();
                     $kuiShouInfo = $kuaishouService->kuaishouUserinfo($accountInfo['access_token']);
                     if ($kuiShouInfo['code'] == 0) {
                         $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                         return result(-1, '此帐号授权过期');
                     }
                 } else {
                     if ($accountInfo['refresh_token_expires_in'] < 0) {
                         $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                         return result(-1, '此帐号授权过期');
                     }
                     $kuaishouService = new KuaishouService();
                     $kuiShouInfo = $kuaishouService->kuaishouRefreshToken($accountInfo['refresh_token_expires_in']);
                     if ($kuiShouInfo['code'] == 0) {
                         $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                         return result(-1, '此帐号授权过期');
                     } else { // 重新授权账号
                         $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                         $user = $FigureThreePartiesAccountModel->where('open_id', $kuiShouInfo['open_id'])->find();
                         $threeAccountData = array(
                             'account_name' => $kuiShouInfo['user_info']['name'],
                             'avatar' => $kuiShouInfo['user_info']['head'],
                             'access_token' => $kuiShouInfo['access_token'],
                             'expires_in' => $kuiShouInfo['expires_in'] + time(),
                             'refresh_token' => $kuiShouInfo['refresh_token'],
                         );
                         if ($user) {
                             $FigureThreePartiesAccountModel->where(['id' => $user['id']])->update($threeAccountData);
                         } else {
                             $FigureThreePartiesAccountModel->save($threeAccountData);
                         }
                     }
                 }*/
            } elseif ($param['type'] == 3) {
                $ClipProjectWhere = ['is_shipinghao' => 1];
                $videoCount = count($param['set_time']);
                $tally = sysconfig('tally', 'shipinghao_video');
                if ($user['balance'] < $videoCount * $tally) {
                    return result(-2, '余额不足，请充值');
                }

            } elseif ($param['type'] == 4) {
                $videoCount = count($param['set_time']);
                $tally = sysconfig('tally', 'xiaohongshu_video');
                if ($user['balance'] < $videoCount * $tally) {
                    return result(-2, '余额不足，请充值');
                }
                $ClipProjectWhere = ['is_xiaohongshu' => 1];
                /*      $apiService = new ApiService();
                      $resultUserInfo = $apiService->xiaohongshuUserInfo(['cookie' => $accountInfo['cookie']]);
                      if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                          if (isset($resultUserInfo['data']['response_body'])) {
                              if ($resultUserInfo['data']['response_body']['code'] != 0) {
                                  $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                                  return result(-1, '此帐号授权过期');
                              }
                          }
                      }*/
            }
            $ThreeVideoTaskModel->startTrans();
            $ThreeVideoTaskModel->save($data);
            $copywiring = [];
            if (isset($param['copywiring'])) {
                $copywiring = explode(',', $param['copywiring']);
                if ($copywiring) {
                    $ThreeCopywritingModel = new ThreeCopywriting();
                    foreach ($copywiring as $value) {
                        $copywiringData['copywriting_id'] = $value;
                        $copywiringData['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $ThreeCopywritingModel->save($copywiringData);
                    }
                }
            }
            $titleId =[];
            if(isset($param['title_id'])){
                $titleId = explode(',', $param['title_id']);
                if ($titleId) {
                    $ThreeTitleModel = new ThreeTitle();
                    foreach ($titleId as $titleIdvalue) {
                        $titleData['title_id'] = $titleIdvalue;
                        $titleData['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $ThreeTitleModel->save($titleData);
                    }
                }
            }


            if ($param['clip_id']) {
                $clipId = explode(',', $param['clip_id']);
                if ($clipId) {
                    $clipModel = new ThreeClipVideo();
                    foreach ($copywiring as $value) {
                        $clipData['clip_id'] = $value;
                        $clipData['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                        $clipModel->save($clipData);
                    }
                }
            } else {
                return result(-1, '请选择视频');
            }
            $ClipProject = new ClipProject();

            $clipProjectList = $ClipProject->where('mission_id', 'in', $clipId)->where($ClipProjectWhere)->where(['status' => 5])->select()->toArray();

            if (empty($clipProjectList)) {
                return result(-1, '无视频发布');
            }

            foreach ($param['set_time'] as $key => $value) {
                if (isset($clipProjectList[$key])) {
                    $threeReleaseVideoTask['uid'] = $param['uid'];
                    $threeReleaseVideoTask['three_video_task_id'] = $ThreeVideoTaskModel['id'];
                    $threeReleaseVideoTask['clip_project_video_id'] = $clipProjectList[$key]['id'];
                    $threeReleaseVideoTask['three_account_id'] = $value['dyAccountId'];
                    $threeReleaseVideoTask['channle_type'] = $param['type'];
                    $threeReleaseVideoTask['release_time'] = strtotime($value['publishTime']);
                    $threeReleaseVideoTask['name'] = $param['name'];
                    $threeReleaseVideoTask['create_time'] = time();
                    if (isset($param['topic_list'])) {
                        $threeReleaseVideoTask['topic_list'] = $param['topic_list'];
                    }
                    if (isset($param['topic_name'])) {
                        $threeReleaseVideoTask['topic_name'] = $param['topic_name'];
                    }
                    if (isset($param['anchorUrl'])) {
                        $threeReleaseVideoTask['anchorUrl'] = $param['anchorUrl'];
                    }
                    if (isset($param['anchorTitle'])) {
                        $threeReleaseVideoTask['anchorTitle'] = $param['anchorTitle'];
                    }
                    if (isset($param['anchorId'])) {
                        $threeReleaseVideoTask['anchorId'] = $param['anchorId'];
                    }
                    if ($copywiring) {
                        $ThreeCopywritingCount = count($copywiring);
                        $ThreeCopywritingIndex = mt_rand(0, $ThreeCopywritingCount - 1);
                        $threeReleaseVideoTask['copywriting_id'] = $copywiring[$ThreeCopywritingIndex];
                    }
                    if ($titleId) {
                        $titleIdCount = count($titleId);
                        $titleIdIndex = mt_rand(0, $titleIdCount - 1);
                        $threeReleaseVideoTask['ai_title'] = $titleId[$titleIdIndex];
                    }

                    if(isset($param['title']) && $param['title'] ){
                    //    $titleArray= explode('||', $param['title']);
                        $titleArrayCount = count($param['title']);
                        $titleArrayIndex = mt_rand(0, $titleArrayCount - 1);
                        $threeReleaseVideoTask['title'] = $param['title'][$titleArrayIndex]['title'];
                    }

                    $threeReleaseVideoTask['log_no'] = getPayNo('JZ');
                    $ThreeVideoReleaseTaskModel->insert($threeReleaseVideoTask);
                    $FigureThreePartiesAccount->where(['id' => $value['dyAccountId']])
                        ->inc('totle_task')->inc('released_task')->update();
                    if ($param['type'] == 1) {
                        $ClipProject->where(['id' => $clipProjectList[$key]['id']])->update(['is_douyin' => 2]);
                        user_balance_used($param['uid'], $threeReleaseVideoTask['log_no'], 2, 18);

                    } elseif ($param['type'] == 2) {
                        $ClipProject->where(['id' => $clipProjectList[$key]['id']])->update(['is_kuaishou' => 2]);
                       // user_balance_used($param['uid'], $threeReleaseVideoTask['log_no'], 2, 19);
                    } elseif ($param['type'] == 3) {
                        $ClipProject->where(['id' => $clipProjectList[$key]['id']])->update(['is_shipinghao' => 2]);
                        user_balance_used($param['uid'], $threeReleaseVideoTask['log_no'], 2, 20);
                    } elseif ($param['type'] == 4) {
                        $ClipProject->where(['id' => $clipProjectList[$key]['id']])->update(['is_xiaohongshu' => 2]);
                        user_balance_used($param['uid'], $threeReleaseVideoTask['log_no'], 2, 21);
                    }
                }

            }

            $ThreeVideoTaskModel->commit();
            return result(0, '添加成功', $ThreeVideoTaskModel);
        } catch (\Exception $exception) {
            $ThreeVideoTaskModel->rollback();
            return result(-1, $exception->getMessage() . $exception->getLine());
        }
    }


    public function xiaohongshuInfo()
    {
        $request = $this->request;
        $param = $request->param();
        $FigureThreePartiesAccount = new  FigureThreePartiesAccount();
        $FigureThreePartiesAccountInfo = $FigureThreePartiesAccount->where(['id' => $param['id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $resultUserInfo = $apiService->xiaohongshuUserInfo(['cookie' => $FigureThreePartiesAccountInfo['cookie']]);
        return result(0, 'success', $resultUserInfo);
    }

    public function VideoTaskList()
    {
        try {
            $uid = input('uid');
            $ThreeVideoTaskModel = new ThreeVideoTask();
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where = 'uid = ' . $uid;
            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%' ";
            }
            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND channle_type = {$type} ";
            }

//            if (!empty(input('account_group_id'))) {
//                $account_group_id = input('account_group_id');
//                $where .= " AND account_group_id = {$account_group_id} ";
//            }
            if (!empty(input('three_account_id'))) {
                $three_account_id = input('three_account_id');
                $where .= " AND three_account_id = {$three_account_id} ";
            }
            $total = $ThreeVideoTaskModel->where($where)->count();
            if ($total) {
                $list = $ThreeVideoTaskModel->where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
                foreach ($list as $key => $value) {
                    $list[$key]['published_task'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_video_task_id' => $value['id']])->count();
                    $list[$key]['published_fail_task'] = $ThreeVideoReleaseTaskModel->where(['status' => 4, 'three_video_task_id' => $value['id']])->count();
                    $list[$key]['published_wait_task'] = $ThreeVideoReleaseTaskModel
                        ->where(['three_video_task_id' => $value['id']])->whereIn('status',  '1,2,5,6')->count();

                    $list[$key]['totle_task'] = $ThreeVideoReleaseTaskModel->where(['three_video_task_id' => $value['id']])->count();
                    if($list[$key]['totle_task'] >0){
                        $list[$key]['percentage'] = bcmul(bcdiv($list[$key]['published_task'], $list[$key]['totle_task'], 2), 100);

                    }else{
                        $list[$key]['percentage'] = 0;
                    }

                }
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function VideoTaskStatistics()
    {

        $id = input('id');
        if ($id) {

            $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
            $data['published_task'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_video_task_id' => $id])->count();
            $data['published_fail_task'] = $ThreeVideoReleaseTaskModel->where(['status' => 4, 'three_video_task_id' => $id])->count();
            $data['published_wait_task'] = $ThreeVideoReleaseTaskModel->where(['three_video_task_id' => $id])->where('status', 'in', ['1,2,5,6'])->count();
            $data['like_count'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_video_task_id' => $id])->sum('like_count');
            $data['comment'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_video_task_id' => $id])->sum('comment');
            $data['exposure_count'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_video_task_id' => $id])->sum('exposure_count');
            $data['totle_task'] = $ThreeVideoReleaseTaskModel->where(['three_video_task_id' => $id])->count();

        } else {
            $three_account_id = input('three_account_id');
            $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
            $data['published_task'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_account_id' => $three_account_id])->count();
            $data['published_fail_task'] = $ThreeVideoReleaseTaskModel->where(['status' => 4, 'three_account_id' => $three_account_id])->count();
            $data['published_wait_task'] = $ThreeVideoReleaseTaskModel->where(['three_account_id' => $three_account_id])->where('status', 'in', ['1,2,5,6'])->count();
            $data['like_count'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_account_id' => $three_account_id])->sum('like_count');
            $data['comment'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_account_id' => $three_account_id])->sum('comment');
            $data['exposure_count'] = $ThreeVideoReleaseTaskModel->where(['status' => 3, 'three_account_id' => $three_account_id])->sum('exposure_count');
            $data['totle_task'] = $ThreeVideoReleaseTaskModel->where(['three_video_task_id' => $three_account_id]);
        }

        return result(0, '操作成功', $data);

    }


    public function delTask()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $id = input('id');
        $ThreeVideoTaskinfo = ThreeVideoTask::where(['id' => $id])->find();
        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $ThreeVideoReleaseTaskModel->where(['status' => 2, 'clip_project_video_id' => $id])->update(['delete_time' => time()]);
        $ThreeVideoTaskinfo->delete();
        return result(0, '操作成功', []);
    }

    public function endTask()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $id = input('id');
        ThreeVideoTask::where(['id' => $id])->update(['status' => 2]);
        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $ThreeVideoReleaseTaskModel->where('status', '<>', '3')->where(['clip_project_video_id' => $id])->update(['status' => 7]);

        return result(0, '操作成功', []);
    }


    public function VideoList()
    {
        try {
            $uid = input('uid');
            $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where = 'uid = ' . $uid;
            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%' ";
            }
            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND channle_type = {$type} ";
            }

            if (!empty(input('account_group_id'))) {
                $account_group_id = input('account_group_id');
                $where .= " AND account_group_id = {$account_group_id} ";
            }
            if (!empty(input('three_account_id'))) {
                $three_account_id = input('three_account_id');
                $where .= " AND three_account_id = {$three_account_id} ";
            }

            if (!empty(input('task_id'))) {
                $task_id = input('task_id');
                $where .= " AND three_video_task_id = {$task_id} ";
            }

            if (!empty(input('status'))) {
                $status = input('status');
                if ($status) {
                    if ($status == 1) {
                        $where .= " AND status  in (1,2,5,6) ";
                    } else {
                        $where .= " AND status  = {$status} ";
                    }
                }

            }
            $FigureAiTitleModel = new FigureAiTitle();
            $total = $ThreeVideoReleaseTaskModel->where($where)->count();
            $FigureAicreateModel = new FigureAicreate();
            if ($total) {
                $list = $ThreeVideoReleaseTaskModel->where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                foreach ($list as $key => $value) {
                  /*  if ($value['copywriting_id']) {
                        $FigureAicreateInfo = $FigureAicreateModel->where(['id' => $value['copywriting_id']])->find();
                        $list[$key]['copywriting'] = $FigureAicreateInfo['question'];
                    } else {
                        $list[$key]['copywriting'] = '';
                    }*/
//                    if ($value['ai_title']) {
//                        $FigureAicreateInfo = $FigureAiTitleModel->where(['id' => $value['ai_title']])->find();
//                        $list[$key]['ai_title'] = $FigureAicreateInfo['question'];
//                    } else {
//                        $list[$key]['ai_title'] = '';
//                    }
                    $list[$key]['release_time'] = date('Y-m-d H:i', $value['release_time']);
                    $FigureThreePartiesAccountInfo = FigureThreePartiesAccount::where(['id' => $value['three_account_id']])->find();
                    $list[$key]['account_name'] = $FigureThreePartiesAccountInfo['account_name'];
                    $list[$key]['avatar'] = $FigureThreePartiesAccountInfo['avatar'];
                    $FigureThreePartiesAccountInfo = ClipProject::where(['id' => $value['clip_project_video_id']])->find();
                    $list[$key]['video_src'] = $FigureThreePartiesAccountInfo['complete_video'];
                    $list[$key]['video_cover'] = $FigureThreePartiesAccountInfo['complete_cover'];

                }
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function statistics()
    {
        $uid = input('uid');

        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $douyinTotal = ThreeVideoReleaseTask::where(['uid' => $uid])
            ->field('sum(comment) as comment_total ,sum(exposure_count) as exposure_count_total ,sum(like_count) as like_count_total,channle_type ')
            ->find();
        $data['douyin_account_count'] = FigureThreePartiesAccount::where(['uid' => $uid])->where(['type' => 1,'is_delete' => 1])->count();
        $data['kuaishou_account_count'] = FigureThreePartiesAccount::where(['uid' => $uid])->where(['type' => 2,'is_delete' => 1])->count();
        $data['shipinghao_account_count'] = FigureThreePartiesAccount::where(['uid' => $uid])->where(['type' => 3,'is_delete' => 1])->count();
        $data['xiaohong_account_count'] = FigureThreePartiesAccount::where(['uid' => $uid])->where(['type' => 4,'is_delete' => 1])->count();
        $data['account_count'] = FigureThreePartiesAccount::where(['uid' => $uid])->where(['is_delete' => 1])->count();
        $data['comment_total'] = $douyinTotal['comment_total'] ? $douyinTotal['comment_total'] : 0;
        $data['exposure_count_total'] = $douyinTotal['exposure_count_total'] ? $douyinTotal['exposure_count_total'] : 0;
        $data['like_count_total'] = $douyinTotal['like_count_total'] ? $douyinTotal['like_count_total'] : 0;

        return result(0, 'success', $data);


    }

    public function xiaohongshuTopic()
    {
        $request = $this->request;
        $param = $request->param();
        $FigureThreePartiesAccount = new  FigureThreePartiesAccount();
        $FigureThreePartiesAccountInfo = $FigureThreePartiesAccount->where(['id' => $param['three_account_id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $resultUserInfo = $apiService->xiaohongshuUserInfo(['cookie' => $FigureThreePartiesAccountInfo['cookie']]);
        if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
            if (isset($resultUserInfo['data']['response_body'])) {
                if ($resultUserInfo['data']['response_body']['code'] != 0) {
                    $FigureThreePartiesAccount->where(['id' => $resultUserInfo['id']])->update(['status' => 2]);
                    return result(-1, '此帐号授权过期');
                }
            }
        }
        $result = $apiService->xiaohongshuTopic(['cookie' => $FigureThreePartiesAccountInfo['cookie'], 'keyword' => $param['keyword']]);
        return result(0, 'success', $result['data']['data']['topic_info_dtos']);
    }

    public function accountGroupUser()
    {
        try {
            $uid = input('uid');
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $where = 'uid = ' . $uid;
            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = {$type} ";
            }

            $where .= " AND account_count > 0 ";
            $list = ThreeAccountGroup::where($where)->order('create_time', 'desc')
                ->select();
            foreach ($list as $key => $value) {
                $accountList = FigureThreePartiesAccount::where(['account_group_id' => $value['id']])->select()->toArray();
                if ($accountList) {
                    $accountId = array_column($accountList, 'id');
                    $videoTotal = ThreeVideoReleaseTask::where('three_account_id', 'in', $accountId)
                        ->field('sum(comment) as comment_total ,sum(exposure_count) as exposure_count_total ,sum(like_count) as like_count_total ')
                        ->find();

                    $list[$key]['comment'] = $videoTotal['comment_total'] ? $videoTotal['comment_total'] : 0;
                    $list[$key]['exposure_count'] = $videoTotal['exposure_count'] ? $videoTotal['exposure_count'] : 0;
                    $list[$key]['like_count'] = $videoTotal['like_count'] ? $videoTotal['like_count'] : 0;
                }
            }


            return result(0, 'success', $list);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function poiList()
    {

        $request = $this->request;
        $param = $request->param();
        $douyin_set = sysconfig('forward');
        $client_key = $douyin_set['d_key'];
        $client_secret = $douyin_set['d_secret'];
        $client_url = "https://open.douyin.com/oauth/client_token/?grant_type=client_credential&client_key=" . $client_key . "&client_secret=" . $client_secret;
        $client_obj = httpGet($client_url);
        $client_data = json_decode($client_obj, true);

        if ($client_data['message'] =='success') {
            $access_token = $client_data['data']['access_token'];
            $data['city'] = $param['city'];
            $data['keyword'] = $param['keyword'];
            $dataGET = http_build_query($data);
            $ticket_client_url = "https://open.douyin.com/poi/search/keyword/?" . $dataGET;
            $ticket_client_obj = share_wtw_request($ticket_client_url, null, [
                'Content-Type: application/json; charset=utf-8',
                'access-token: ' . $access_token
            ]);
            $ticket_client_obj = \json_decode($ticket_client_obj, true);
            return result(0, 'success', $ticket_client_obj['data']['pois']);
        } else {
            return result(-1, $client_data['data']['description']);
        }


    }

    public function publisheKuaishou()
    {
        $id = input('id');
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'kuaishou_video');
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeVideoReleaseTaskInfo = $ThreeVideoReleaseTask->where(['id' => $id])->find();
        if (empty($ThreeVideoReleaseTaskInfo)) {
            return result(-1, '此数据不能重新发布');
        }

        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ClipProject = new ClipProject();
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->find();
        $data['access_token'] = $accountInfo['access_token'];
        if ($accountInfo['expires_in'] > time()) {
            $kuaishouService = new KuaishouService();
            $kuiShouInfo = $kuaishouService->kuaishouUserinfo($accountInfo['access_token']);
            if ($kuiShouInfo['code'] == 0) {
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->dec('released_task')->update();
                }
                $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_kuaishou' => 1]);;
                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['status' => 4,]);
                $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->update(['status' => 2]);
                return result(-1, '发布失败');
            }
            $data['access_token'] = $accountInfo['access_token'];
        } else {
            if ($accountInfo['refresh_token_expires_in'] < 0) {
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->dec('released_task')->update();
                }
                $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_kuaishou' => 1]);
                //user_balance_used($ThreeVideoReleaseTaskInfo['uid'], $ThreeVideoReleaseTaskInfo['log_no'], 1, 19);
                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['status' => 4,]);
                $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->update(['status' => 2]);
                return result(-1, '发布失败');

            }
            $kuaishouService = new KuaishouService();
            $kuiShouInfo = $kuaishouService->kuaishouRefreshToken($accountInfo['refresh_token_expires_in']);
            if ($kuiShouInfo['code'] == 0) {
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->dec('released_task')->update();
                }
                $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_kuaishou' => 1]);;
                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['status' => 4,]);
                $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->update(['status' => 2]);
                return result(-1, '发布失败');

            } else { // 重新授权账号
                $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                $user = $FigureThreePartiesAccountModel->where('open_id', $kuiShouInfo['open_id'])->find();
                $threeAccountData = array(
                    'create_time' => $kuiShouInfo['data']['user_info']['name'],
                    'avatar' => $kuiShouInfo['data']['user_info']['head'],
                    'access_token' => $kuiShouInfo['data']['access_token'],
                    'expires_in' => $kuiShouInfo['data']['expires_in'] + time(),
                    'refresh_token' => $kuiShouInfo['data']['refresh_token'],
                );
                if ($user) {
                    $FigureThreePartiesAccountModel->where(['id' => $user['id']])->update($threeAccountData);
                } else {
                    $FigureThreePartiesAccountModel->save($threeAccountData);
                }
                $data['access_token'] = $kuiShouInfo['data']['access_token'];
            }
        }
        $data['merchant_product_id'] = $ThreeVideoReleaseTaskInfo['merchant_product_id'];
        $data['anchorUrl'] = $ThreeVideoReleaseTaskInfo['anchorUrl'];
        $data['anchorTitle'] = $ThreeVideoReleaseTaskInfo['anchorTitle'];
        $data['anchorId'] = $ThreeVideoReleaseTaskInfo['anchorId'];

        $clipProjctInfo = $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->find();
        $data['complete_cover'] = $clipProjctInfo['complete_cover'];
        $data['complete_video'] = $clipProjctInfo['complete_video'];

        if ($ThreeVideoReleaseTaskInfo['ai_title']) {
            $FigureAiTitleModel = new FigureAiTitle();
            $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $ThreeVideoReleaseTaskInfo['ai_title']])->find();
            $data['caption'] = $FigureAiTitleInfo['answer'];
        }

            $result = $kuaishouService->releaseKuaishuoVideo($data);
            if ($result['code'] == 1) {
                if ($ThreeVideoReleaseTaskInfo['status'] == 4) {
                    user_balance_used($ThreeVideoReleaseTaskInfo['uid'], $ThreeVideoReleaseTaskInfo['log_no'], 2, 19);
                }
                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                    'status' => 3,
                    'photo_id' => $result['data']['photo_id'],

                ]);
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                if ($taskCount == 0) {

                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->inc('published_task')->dec('released_task')->update();
                    $threeVideoTaskModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])->update(['status' => 3]);
                }
                $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_kuaishou' => 3]);

                if ($clipProjctInfo['is_douyin'] == 3 &&  $clipProjctInfo['is_shipinghao'] ==3  &&  $clipProjctInfo['is_xiaohongshu'] ==3){
                    $clipProjctInfo->delete();
                }
            } else {
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->dec('released_task')->update();
                }
             //   $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_kuaishou' => 1]);

                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                    'status' => 4,
                ]);
            }
   /*     } else {
            return result(-1, '发布失败');

        }*/


        return result(0, '发布成功');
    }

    public function publishDouyin()
    {
        $id = input('id');
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
//
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeVideoReleaseTaskInfo = $ThreeVideoReleaseTask->where(['id' => $id])->find();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ClipProject = new ClipProject();
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->find();
        $data['cookie'] = $accountInfo['cookie'];
        $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
        if ($liuguanResult['code'] == 1) {
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $resultUserInfo = $apiService->douyinAuthorizeUserInfo(['cookie' => $accountInfo['cookie']]);
            if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                if ($resultUserInfo['data']['status_code'] != 0) { // 账号过期
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->update(['status' => 2]);
                    return result(-1, '账号过期');
                }
            } else {
                return result(-1, '发布失败111');
            }
            $threeVideoTaskInfo = $threeVideoTaskModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])->find();
            $data['poiName'] = $threeVideoTaskInfo['poi_address'];
            $data['poiId'] = $threeVideoTaskInfo['poi'];
            $data['proxy'] = $liuguanResult['data']['ip'];
            $clipProjctInfo = $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->find();
            $data['uploadPoster'] = $clipProjctInfo['complete_cover'];
            $data['video'] = $clipProjctInfo['complete_video'];
            if ($ThreeVideoReleaseTaskInfo['ai_title']) {
                $FigureAiTitleModel = new FigureAiTitle();
                $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $ThreeVideoReleaseTaskInfo['ai_title']])->find();
                $data['description'] = $FigureAiTitleInfo['answer'].'#'.$FigureAiTitleInfo['challenges'];
            }

            if ($ThreeVideoReleaseTaskInfo['status'] == 4) {
                $tally = sysconfig('tally', 'douyin_video');
                if ($user['balance'] < $tally) {
                    return result(-2, '余额不足，请充值');
                }

            }
            $result = $apiService->releaseDouyinVideo($data);
            if ($result['code'] == 1) {
                if ($ThreeVideoReleaseTaskInfo['status'] == 4) {
                    user_balance_used($ThreeVideoReleaseTaskInfo['uid'], $ThreeVideoReleaseTaskInfo['log_no'], 3, 18);
                }
                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                    'status' => 3,
                    'item_id' => $result['data']['item_id'],
                    'logid' => $result['data']['extra']['logid'],
                ]);


                $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_douyin' => 3]);

                if ($clipProjctInfo['is_kuaishou'] == 3 &&  $clipProjctInfo['is_shipinghao'] ==3  &&  $clipProjctInfo['is_xiaohongshu'] ==3){
                    $clipProjctInfo->delete();
                }
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->inc('published_task')->dec('released_task')->update();
                    $threeVideoTaskModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])->update(['status' => 3]);

                }
            } else {
                return result(-1, '发布失败');
            }

        } else {
            return result(-1, 'ip获取失败');
        }
        return result(0, '发布成功');
    }

    public function uploadShipinghaoVideo()
    {

        $id = input('id');
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'kuaishou_video');
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $ThreeVideoReleaseTaskInfo = $ThreeVideoReleaseTask->where(['id' => $id, 'status' => 4])->find();
        if (empty($ThreeVideoReleaseTaskInfo)) {
            return result(-1, '此数据不能重新发布');
        }

        $ClipProject = new ClipProject();
        $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
        $accountInfo = $FigureThreePartiesAccountModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $clipProjctInfo = $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->find();
        $data['video'] = $clipProjctInfo['complete_video'];
        $data['cookie'] = $accountInfo['cookie'];
        $result = $apiService->uploadShipinghaoVideo($data);
        if ($result['code'] == 1 && isset($result['data']['task_id'])) {
            $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['task_id' => $result['data']['task_id'], 'status' => 5]);

        } else {
            $taskCount = $ThreeVideoReleaseTask
                ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                ->where('status', 'in', [1, 2])->count();
            if ($taskCount == 0) {
                $FigureThreePartiesAccountModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                    ->dec('released_task')->update();
            }
         //   $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_shipinghao' => 1]);

            $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                'status' => 4,
            ]);
            return result(-1, '发布失败');
        }
        return result(0, '上传成功');

    }

    public function releaseShipinghao()
    {
        $id = input('id');
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'douyin_video');
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeVideoReleaseTaskInfo = $ThreeVideoReleaseTask->where(['id' => $id])->find();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ClipProject = new ClipProject();
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $data['cookie'] = $accountInfo['cookie'];
        $data['task_id'] = $ThreeVideoReleaseTaskInfo['task_id'];
        $result = $apiService->shipinghaoVideoUploadStatus($data);;
        if ($result['code'] == 1) {
            if ($result['data']['status'] == 'completed' && isset($result['data']['result']['file_path'])) {
                $data['cookie'] = $accountInfo['cookie'];
                $data['task_id'] = $ThreeVideoReleaseTaskInfo['task_id'];
                $data['timing'] = $ThreeVideoReleaseTaskInfo['release_time'];
                $threeVideoTaskInfo = $threeVideoTaskModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])->find();
                $data['city'] = $threeVideoTaskInfo['city'];
                $clipProjctInfo = $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->find();
                $data['thumbnail'] = $clipProjctInfo['complete_cover'];

                /* if ($value['copywriting_id']) {
                     $FigureAicreateInfo = $FigureAicreateModel->where(['id' => $value['copywriting_id']])->find();
                     $data['title'] = $FigureAicreateInfo['question'];
                 }*/
                if ($ThreeVideoReleaseTaskInfo['ai_title']) {
                    $FigureAiTitleModel = new FigureAiTitle();
                    $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $ThreeVideoReleaseTaskInfo['ai_title']])->find();
                    $data['title'] = $FigureAiTitleInfo['answer'];
                }
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                } else {
                    $apiService = new ApiService();
                }
                $result = $apiService->releaseShipinghaoVideo($data);
                if ($result['code'] == 1) {
                    if ($result['data']['data']['status'] == 4) {
                        $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['status' => 3]);
                        $taskCount = $ThreeVideoReleaseTask
                            ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                            ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                        if ($taskCount == 0) {
                            $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                                ->inc('published_task')->dec('released_task')->update();
                            $threeVideoTaskModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])->update(['status' => 3]);
                        }
                    } else {
                        $taskCount = $ThreeVideoReleaseTask
                            ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                            ->where('status', 'in', [1, 2])->count();
                        if ($taskCount == 0) {
                            $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                                ->dec('released_task')->update();
                        }
                        //$ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_shipinghao' => 1]);

                        $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                            'status' => 4,
                        ]);
                        return result(-1, '发布失败');
                    }
                }
            }
        } else {
            return result(-1, '发布失败');
        }

        return result(0, '发布成功');
    }

    public function releaseXiaohongshu()
    {
        $id = input('id');
        $uid = input('uid');
        $FigureAicreateModel = new FigureAicreate();
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'douyin_video');
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeVideoReleaseTaskInfo = $ThreeVideoReleaseTask->where(['id' => $id])->find();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ClipProject = new ClipProject();

        $data = [];
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->find();
        $data['cookie'] = $xiaohongshuUserInfoData['cookie'] = $accountInfo['cookie'];
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $xiaohongshuUserInfo = $apiService->xiaohongshuUserInfo($xiaohongshuUserInfoData);



        if ($xiaohongshuUserInfo['code'] == 1) {
            if (isset($xiaohongshuUserInfo['data']['response_body']) && $xiaohongshuUserInfo['data']['response_body']['code'] == 0) {
                if ($ThreeVideoReleaseTaskInfo['copywriting_id']) {
                    $FigureAicreateInfo = $FigureAicreateModel->where(['id' => $ThreeVideoReleaseTaskInfo['copywriting_id']])->find();
                    $data['desc'] = $FigureAicreateInfo['question'];
                }
                if ($ThreeVideoReleaseTaskInfo['ai_title']) {
                    $FigureAiTitleModel = new FigureAiTitle();
                    $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $ThreeVideoReleaseTaskInfo['ai_title']])->find();
                    $data['title'] = $FigureAiTitleInfo['answer'];
                }
                $clipProjctInfo = $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->find();
                $data['cover'] = $clipProjctInfo['complete_cover'];
                $data['video'] = $clipProjctInfo['complete_video'];
                $data['topic_list'] = $clipProjctInfo['topic_list'];

                $releaseVideoInfo = $apiService->releaseXiaohongshuVideo($data);


                if ($releaseVideoInfo['code'] == 1) {
                    if ($releaseVideoInfo['data']['result'] == 0) {
                        if ($ThreeVideoReleaseTaskInfo['status'] == 4) {
                            user_balance_used($ThreeVideoReleaseTaskInfo['uid'], $ThreeVideoReleaseTaskInfo['log_no'], 3, 21);
                        }
                        $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                            'status' => 3,
                            'share_link' => $releaseVideoInfo['data']['share_link'],
                            'xiaohongshu_id' => $releaseVideoInfo['data']['data']['id'],
                        ]);
                        $taskCount = $ThreeVideoReleaseTask
                            ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                            ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                        if ($taskCount == 0) {
                            $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                                ->inc('published_task')->dec('released_task')->update();
                            $threeVideoTaskModel->where(['id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])->update(['status' => 3]);
                        }

                        $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_xiaohongshu' => 3]);

                        if ($clipProjctInfo['is_douyin'] == 3 &&  $clipProjctInfo['is_shipinghao'] ==3  &&  $clipProjctInfo['is_kuaishou'] ==3){
                            $clipProjctInfo->delete();
                        }
                        return result(0, '发布成功');
                    } else {
                        $taskCount = $ThreeVideoReleaseTask
                            ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                            ->where('status', 'in', [1, 2])->count();
                        if ($taskCount == 0) {
                            $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                                ->dec('released_task')->update();
                        }
                   //     $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_xiaohongshu' => 1]);

                        $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                            'status' => 4,
                        ]);
                    }
                    return result(-1, '发布失败');
                } else {
                    $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update([
                        'status' => 1,

                    ]);
                    return result(-1, '发布失败');
                }

            } else {

                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $ThreeVideoReleaseTaskInfo['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])
                        ->dec('released_task')->update();
                }
                $ClipProject->where(['id' => $ThreeVideoReleaseTaskInfo['clip_project_video_id']])->update(['is_xiaohongshu' => 1]);
                user_balance_used($ThreeVideoReleaseTaskInfo['uid'], $ThreeVideoReleaseTaskInfo['log_no'], 3, 21);
                $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['status' => 4]);
                $FigureThreePartiesAccount->where(['id' => $ThreeVideoReleaseTaskInfo['three_account_id']])->update(['status' => 2]);

            }
        } else {
            return result(-1, '账号失效');
            $ThreeVideoReleaseTask->where(['id' => $ThreeVideoReleaseTaskInfo['id']])->update(['status' => 1]);
        }
    }

    public function douyinCommentList()
    {
        $id = input('id');
        $request = $this->request;
        $param = $request->param();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();

        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTaskModel->where(['id' => $id])->find();
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $taskList['three_account_id']])->find();
        $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);

        $data['proxy'] = $liuguanResult['data']['ip'];
        $data['cursor'] = $param['cursor'];
        $data['count'] = $param['count'];
        $data['aweme_id'] = $taskList['item_id'];
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $douyinOneComment = $apiService->douyinCommentList($data);

        if ($douyinOneComment['code'] == 1) {
          if ($douyinOneComment['data']['comments']) {
                foreach ($douyinOneComment['data']['comments'] as $key => $value) {
                    $douyinOneComment['data']['comments'][$key]['create_time'] = date('Y-m-d H:i');
                }
            }
            return result(0, 'success', $douyinOneComment['data']);


        } else {
            return result(-1, '获取失败');
        }
    }

    public function douyinCommentTwoList(){
    $request = $this->request;
    $param = $request->param();
    $id = input('id');
    $request = $this->request;
    $param = $request->param();
    $FigureThreePartiesAccount = new FigureThreePartiesAccount();

    $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
    $taskList = $ThreeVideoReleaseTaskModel->where(['id' => $id])->find();
    $accountInfo = $FigureThreePartiesAccount->where(['id' => $taskList['three_account_id']])->find();

    $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
    $dataTwo['proxy'] = $liuguanResult['data']['ip'];
    $dataTwo['cursor'] = $param['cursor'];;
    $dataTwo['count'] = $param['count'];
    $dataTwo['aweme_id'] = $taskList['item_id'];
    $dataTwo['comment_id'] = $param['comment_id'];
    if (sysconfig('account', 'operation_version') == 2) {
        $apiService = new AgentApiService();
    } else {
        $apiService = new ApiService();
    }
    $douyinTwoComment = $apiService->douyinLastCommentList($dataTwo);
    if($douyinTwoComment['code'] ==1){
        if ($douyinTwoComment['data']['comments']) {
            foreach ($douyinTwoComment['data']['comments'] as $key => $value) {
                $douyinTwoComment['data']['comments'][$key]['create_time'] = date('Y-m-d H:i');
            }
        }
        return result(0, 'success', $douyinTwoComment['data']);
    }else{
        return result(-1, '失败');
    }

}

    public function xiaohongshuCommentList()
    {
        $id = input('id');
        $request = $this->request;
        $param = $request->param();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTaskModel->where(['id' => $id])->find();

        $accountInfo = $FigureThreePartiesAccount->where(['id' => $taskList['three_account_id']])->find();
        $xiaohongshuUserInfoData['cookie'] = $data['cookie'] = $accountInfo['cookie'];
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $xiaohongshuUserInfo = $apiService->xiaohongshuUserInfo($xiaohongshuUserInfoData);



        if (isset($xiaohongshuUserInfo['data']['response_body']) && $xiaohongshuUserInfo['data']['response_body']['code'] == 0) {
            $data['cursor'] = $param['cursor'];
            $data['note_id'] = $taskList['xiaohongshu_id'];
            $xiaohongshuOneComment = $apiService->xiaohongshuCommentList($data);

            if (isset($xiaohongshuOneComment['data']['response_body']) && $xiaohongshuOneComment['data']['response_body']['code'] == 0) {
                return result(0, 'success', $xiaohongshuOneComment['date']['response_body']['data']);
            } else {
                return result(-1, '获取失败2');
            }

        } else {
            return result(-1, '获取失败1');
        }
    }


    public function xiaohongshuTwoCommentList(){
        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $dataTow['cursor'] = $param['cursor'];
        $dataTow['num'] = $param['num'];
        $dataTow['note_id'] = $param['xiaohongshu_id'];
        $dataTow['root_comment_id'] = $param['note_id'];
        $xiaohongshuTwoComment = $apiService->xiaohongshuLastCommentList($dataTow);
        if (isset($xiaohongshuTwoComment['data']['response_body']) && $xiaohongshuTwoComment['data']['response_body']['code'] == 0) {
            return result(0, 'success', $xiaohongshuTwoComment['date']['response_body']['data']);
        } else {
            return result(-1, '获取失败');
        }

    }

    public function kuaishouVideoComment()
    {
        $id = input('id');
        $request = $this->request;
        $param = $request->param();

        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTaskModel->where(['id' => $id])->find();
        $data['aweme_id'] = $taskList['photo_id'];
        $data['pcursor'] = $taskList['pcursor'];
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $douyinTwoComment = $apiService->kuaishouVideoComment($data);
        if ($douyinTwoComment['code'] == 1) {
            return result(0, 'success', $douyinTwoComment['date']);
        }
        return result(-1, 'success', '获取失败');

    }

    public function douyinComment()
    {
        $request = $this->request;
        $param = $request->param();
        $id = input('id');
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();

        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTaskModel->where(['id' => $id])->find();
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $taskList['three_account_id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $resultUserInfo = $apiService->douyinUserInfo(['cookie' => $accountInfo['cookie']]);
        if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
            if ($resultUserInfo['data']['status_code'] != 0) {
                $FigureThreePartiesAccount->where(['id' => $accountInfo['id']])->update(['status' => 2]);
                return result(-1, '此帐号授权过期');
            }
        }
        $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
        if ($liuguanResult['code'] == 1) {
            $send = [
                'cookie' => $accountInfo['cookie'],
                'proxy' => $liuguanResult['data']['ip'],
                'aweme_id' => $taskList['item_id'],
                'reply_id'=> $param['reply_id'],
                'text' =>  $param['text'],
            ];
            $douyinOneComment = $apiService->douyinComment($send);
            if ($douyinOneComment['code'] ==1){
                return result(0, '评论成功');
            }
        }
        return result(-1, '评论失败');
    }

    public function xiaohongshuComment(){
        $request = $this->request;
        $param = $request->param();
        $id = input('id');
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ThreeVideoReleaseTaskModel = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTaskModel->where(['id' => $id])->find();
        $accountInfo = $FigureThreePartiesAccount->where(['id' => $taskList['three_account_id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $resultUserInfo = $apiService->xiaohongshuUserInfo(['cookie' => $accountInfo['cookie']]);
        if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
            if (isset($resultUserInfo['data']['response_body'])) {
                if ($resultUserInfo['data']['response_body']['code'] != 0) {
                    $FigureThreePartiesAccount->where(['id' => $resultUserInfo['id']])->update(['status' => 2]);
                    return result(-1, '此帐号授权过期');
                }
            }
        }
        $send = [
            'cookie' => $accountInfo['cookie'],
            'note_id' => $taskList['xiaohongshu_id'],
            'comment_id'=> $param['comment_id'],
            'content' =>  $param['content'],
        ];
        $douyinOneComment = $apiService->xiaohongshuComment($send);
        if ($douyinOneComment['code'] ==1){
            return result(0, '评论成功');
        }else{
            return result(-1, $douyinOneComment['msg']);
        }
        return result(0, '评论失败');
    }


    public function addTask(){
        $request = $this->request;
        $param = $request->param();
        $ScanTaskModel = new ScanTask();
        if (isset($param['video_id']) &&$param['video_id'] ){
            $videoId = explode(',',$param['video_id']);
        }else{
            $videoId =[];
            $clipProjectModel  =  new ClipProject();
            $clipList = $clipProjectModel->where(['is_douyin' => 1,'mission_id'=>$param['mission_id'] ])->select();
            foreach ($clipList as $value){
                $videoId[] = $value['id'];
            }
        }
        $titleId = explode(',',$param['title_id']);
        $data  = [
            'name'=> $param['name'],
            'uid'=> $param['uid'],
            'mount_type' => $param['mount_type'],
            'poi' => isset($param['poi']) ? $param['poi']:'' ,
            'poi_address' =>isset( $param['poi_address'])? $param['poi_address']:'',
            'release_day_count' => $param['release_day_count'],
            'channle_type' =>  $param['channle_type'],
            'video_num'=>  count($videoId),
            'surplus_num'=>  count($videoId),
            'mission_id'=> $param['mission_id'],
            'select_type' => $param['select_type'],
            'merchant_product_id' => isset($param['merchant_product_id']) ? $param['merchant_product_id']:'',
            'app_id' => isset($param['app_id']) ? $param['app_id']:'',
            'app_title' => isset($param['app_title']) ? $param['app_title']:'',
            'description' => isset($param['description']) ? $param['description']:'',
            'app_url' => isset($param['app_url']) ? $param['app_url']:'',
        ];
        $ScanTaskModel->save($data);
        $scan_task_video  = new ScanTaskVideo();
        $video  = [];
        foreach ($videoId as $key =>   $value){
            $video[$key]['three_video_task_id'] = $value;
            $video[$key]['scan_task'] = $ScanTaskModel->id;
            $video[$key]['create_time'] = time();
        }
        $scan_task_Title = new ScanTaskTitle();
        foreach ($titleId as $titlekey =>   $titleValue){
            $titleArray[$titlekey]['title_id'] = $titleValue;
            $titleArray[$titlekey]['scan_task'] = $ScanTaskModel->id;
            $titleArray[$titlekey]['create_time'] = time();
        }
        $ClipProject = new ClipProject();
        if ($param['channle_type'] == 1){
            $ClipProject->whereIn('id', $videoId)->update(['is_douyin' => 2]);
        }else{
            $ClipProject->whereIn('id',$videoId)->update(['is_kuaishou' => 2]);

        }
        $ClipMission = new ClipMission();
        if ($param['select_type'] ==2){
            if ($param['channle_type'] == 1){
                $ClipMission->whereIn('id', $param['mission_id'])->update(['is_douyin' => 2]);
            }else{
                $ClipMission->whereIn('id',$param['mission_id'])->update(['is_kuaishou' => 2]);
            }
        }
        $scan_task_video->insertAll($video);
        $scan_task_Title->insertAll($titleArray);
        return result(0, '添加成功',$ScanTaskModel);

    }

    public function taskList(){

        try {
            $uid = input('uid');
            $ScanTaskModel = new ScanTask();
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $where =[];
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where[] =  ['uid','=',$uid];
            if (!empty(input('name'))) {
                $name = input('name');
                //$where .= " AND name LIKE '%{$name}%' ";
                $where[] = [
                    "name",
                    "LIKE",
                    "%" .$name . "%"
                ];
            }
            if (!empty(input('type'))) {
                $type = input('type');
                $where[] =  ['channle_type' ,'=',$type];
            }
            $FigureAiTitleModel = new FigureAiTitle();
            $ScanTaskTitleModel = new ScanTaskTitle();
            $total = $ScanTaskModel->where($where)->count();
            $ScanTaskVideo = new ScanTaskVideo();
            $clipResourceModel = new ClipProject();
            if ($total) {
                $list = $ScanTaskModel->where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                $video =[];
                $clip_video_repost = new ClipVideoRepost();
                foreach ($list as $key => $value) {
                    $videoList = $ScanTaskVideo->where(['scan_task' => $value['id']])->select();
                    foreach ($videoList as $videoValue){
                        $videoInfo = $clipResourceModel->where(['id' => $videoValue['three_video_task_id']])->find();
                        if ($videoInfo){
                            $video[] = $videoInfo;
                        }
                    }
                    $titleList  = $ScanTaskTitleModel->where(['scan_task' => $value['id']])->select();
                    $title_list = [];
                    foreach ($titleList as $titleValue){
                        $titleInfo = $FigureAiTitleModel->where('id', $titleValue['id'])->find();
                        if ($titleInfo){
                            $title_list[] = $titleInfo;
                        }
                    }
                    $list[$key]['title_list']  = $title_list;
                    $list[$key]['video_info']  = $video;
                    $list[$key]['published']  = $value['video_num']-$value['surplus_num'];
                    $today = date("Y-m-d");
                    $midnightTimestamp = strtotime($today);
                    $todayCount = $clip_video_repost ->where('create_time', '>', $midnightTimestamp)
                        ->where(['scan_task' => $value['id']])->count();
                    $list[$key]['today_count']  = $todayCount;
                }
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }


    }
    public function taskVideo(){
        $request = $this->request;
        $param = $request->param();
        $ScanTaskVideo = new ScanTaskVideo();
        $clipResourceModel = new ClipProject();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $ScanTaskVideo->where(['scan_task' => $param['id']])->count();
        $list = $ScanTaskVideo->where(['scan_task' => $param['id']])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $ClipVideoRepostModel = new ClipVideoRepost();
        foreach ($list as $key=>  $value){
            $videoInfo = $clipResourceModel->where(['id' => $value['three_video_task_id']])->find();
            $list[$key]['video_info']= $videoInfo;
            $repostInfo = $ClipVideoRepostModel->where(['video_id' => $value['three_video_task_id']])->find();
            if ($repostInfo){
                $list[$key]['repost']= $repostInfo;
            }else{
                $list[$key]['repost']= [];
            }

        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function  terminateTask(){
        $request = $this->request;
        $param = $request->param();
        $ScanTaskModel = new ScanTask();
        $ScanTaskModel->where(['id' =>$param['id'] ])->update(['status' =>$param['status']]);
        return result(0, '修改成功');

    }

    public function eidtTask(){
        $request = $this->request;
        $param = $request->param();
        $ScanTaskModel = new ScanTask();
        $videoId =[];
        if ( $param['select_type'] == 1){

            $videoId =[];
            $clipProjectModel  =  new ClipProject();
            $clipList = $clipProjectModel->where(['mission_id'=>$param['mission_id'] ])->select();
            foreach ($clipList as $value){
                $videoId[] = $value['id'];
            }

        }else{
            $videoId = explode(',',$param['video_id']);
        }

        $titleId = explode(',',$param['title_id']);
        $data  = [
            'name'=> $param['name'],
            //  'mount_type' => $param['mount_type'],
            // 'poi' => isset($param['poi']) ? $param['poi']:'' ,
            //  'poi_address' =>isset( $param['poi_address'])? $param['poi_address']:'',
            'release_day_count' => $param['release_day_count'],
            //  'channle_type' =>  $param['channle_type'],
          //  'video_num'=>  count($videoId),
            //  'surplus_num'=>  count($videoId),
            'mission_id'=> $param['mission_id'],
            'select_type' => $param['select_type'],
        ];
        $scan_task_video  = new ScanTaskVideo();
        $video  = [];
        foreach ($videoId as $key =>   $value){
            $video['three_video_task_id'] = $value;
            $video['scan_task'] = $param['id'];
            $video['create_time'] = time();
            $info =   $scan_task_video->where(['three_video_task_id'=>$value,'scan_task' =>$param['id']])->find();
            $ClipProject = new ClipProject();
            if (empty($info)){
                if ($param['channle_type'] == 1){
                    $ClipProject->whereIn('id', $videoId)->update(['is_douyin' => 2]);
                }else{
                    $ClipProject->whereIn('id',$videoId)->update(['is_kuaishou' => 2]);
                }
                $scan_task_video->save($video);
                $ScanTaskModel->where(['id' => $param['id']])->inc('surplus_num')->inc('video_num')->update();
            }
        }
        $ScanTaskModel->where(['id' => $param['id']])->update($data);
        $scan_task_Title = new ScanTaskTitle();
        foreach ($titleId as $titlekey =>   $titleValue){
            $titleArray[$titlekey]['title_id'] = $titleValue;
            $titleArray[$titlekey]['scan_task'] = $param['id'];
            $titleArray[$titlekey]['create_time'] = time();
        }

        /* if ($video){
             if ($videoId){
                 if ($param['channle_type'] == 1){
                     $ClipProject->whereIn('id', $videoId)->update(['is_douyin' => 2]);
                 }else{
                     $ClipProject->whereIn('id',$videoId)->update(['is_kuaishou' => 2]);

                 }
             }

             $scan_task_video->insertAll($video);
             foreach ($video as $videoValue){

             }
           //  $ScanTaskModel->where(['id' => $param['id']])->inc('video_num',count($video))->inc('surplus_num',count($video))->update($data);
         }else{
             $ScanTaskModel->where(['id' => $param['id']])->update($data);
         }*/


        $titleList = $scan_task_Title->whereIn('scan_task', $param['id'])->select();
        $titleList->delete();

        $scan_task_Title->insertAll($titleArray);
        return result(0, '添加成功',$ScanTaskModel);
    }

    public function delScanTask()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $id = input('id');
        $ThreeVideoTaskinfo = ScanTask::where(['id' => $id])->find();
        $ThreeVideoTaskinfo->delete();
        return result(0, '操作成功', []);
    }

    public function taskInfo(){
        $request = $this->request;
        $param = $request->param();
        $ScanTaskModel = new ScanTask();
        $ScanTaskTitleModel = new ScanTaskTitle();
        $ScanTaskVideoModel = new ScanTaskVideo();
        $info = $ScanTaskModel->where(['id' => $param['id']])->find();
        $titleList = $ScanTaskTitleModel->where(['scan_task' =>  $param['id']])->select()->toArray();
        $info['title_id'] = [];
        if ($titleList){
            $titleId = array_column($titleList,'title_id');
            $info['title_id'] = $titleId;
        }
        $ScanTaskList = $ScanTaskVideoModel->where(['scan_task' =>  $param['id']])->select()->toArray();
        $info['video_id'] = [];
        if ($ScanTaskList){
            $videoId = array_column($ScanTaskList,'three_video_task_id');
            $info['video_id'] = $videoId;

        }
        $ClipTitleModel = new ClipTitle();
        $title = $ClipTitleModel->where(['mission_id' => $info['mission_id']])->find();
        if ($title){
            $info['title'] = $title['title'];
        }else{
            $info['title'] = '';
        }
        return result(0, '操作成功', $info);





    }

    /*    public function commentList()
        {
            $id = input('video_id');
            $threeCommentModel = new ThreeComment();
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $total = $threeCommentModel->where(['task_video_id' => $id, 'top_comment_id' => ''])->count();

            $list = $threeCommentModel->where(['task_video_id' => $id, 'top_comment_id' => ''])->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
            foreach ($list as $key => $value) {
                $lastList = $threeCommentModel->where(['task_video_id' => $id, 'top_comment_id' => $value['cid']])->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select()->toArray();
                $list[$key]['comment'] = $lastList;
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));

        }*/


}